﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
using SchoolCommunicationSystem.Membership;
using SCS.Business;
namespace SchoolCommunicationSystem.Filters
{
    public class BasicAuthenticationMessageHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
               MembershipService _membershipServices = new MembershipService();
            var authHeader = request.Headers.Authorization;

            if (authHeader == null)
            {
                return base.SendAsync(request, cancellationToken);
            }

            if (authHeader.Scheme != "Basic")
            {
                return base.SendAsync(request, cancellationToken);
            }

            var encodedUserPass = authHeader.Parameter.Trim();
            var userPass = Encoding.ASCII.GetString(Convert.FromBase64String(encodedUserPass));
            var parts = userPass.Split(":".ToCharArray());
            var username = parts[0];
            var password = parts[1];
            string[] roles = _membershipServices.GetRolesForUser(username);
            if (roles.Count() == 0)
            {
                return base.SendAsync(request, cancellationToken);
            }
            else
            {
                bool isAdmin = false;
                foreach (string role in roles)
                {
                    if(role.Equals("Admin"))
                    {
                        isAdmin = true;
                    }
                }
                if (!isAdmin)
                { return base.SendAsync(request, cancellationToken);}
            }
            if (!_membershipServices.ValidateUser(username, password,5))
            {
                return base.SendAsync(request, cancellationToken);
            }

            var identity = new GenericIdentity(username, "Basic");
            
            var principal = new GenericPrincipal(identity, roles);
            Thread.CurrentPrincipal = principal;
            if (HttpContext.Current != null)
            {
                HttpContext.Current.User = principal;
            }

            return base.SendAsync(request, cancellationToken);
        }
    }
}